package com.itany.webstock;


import com.alibaba.fastjson.JSON;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/talk/{userId}")
public class WebSocketConfig {

    private Session session;

    private String userName;

    public static CopyOnWriteArraySet<WebSocketConfig> webSocketSet = new CopyOnWriteArraySet<WebSocketConfig>();

    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId){
          this.session=session;
          this.userName="用户"+new Random().nextInt(100);
          System.out.println("========================"+userId+"连接上了");
          webSocketSet.add(this);
    }


    @OnClose
    public void onClose(Session session){
        webSocketSet.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable throwable){

    }

    @OnMessage
    public void onMessage(String message,Session session)throws Exception{
          for(WebSocketConfig cfg:webSocketSet){
              Map<String,Object> map = new HashMap<String,Object>();
              map.put("flag",1);
              map.put("msg",this.userName+":"+message);
              cfg.getSession().getBasicRemote().sendText(JSON.toJSONString(map));
          }
    }


    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}
